let _Vue = null;
export default class VueRouter {
  //注册插件时调用
  static install(Vue) {
    //组件已经安装了
    if (VueRouter.install.installed && _Vue === Vue) return;
    VueRouter.install.installed = true;
    _Vue = Vue;
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;//将router挂载到Vue实例上
          this.$options.router.init();
        }
      }
    });
  }

  constructor(options) {
    this.options = options;
    this.routerMap = {};
    this.data = _Vue.observable({ current: '/' });
  }

  init() {
    this.createRoutreMap();
    this.initComponent(_Vue);
    this.initEvents();
  }

  createRoutreMap() {
    this.options.routes.forEach(item => {
      this.routerMap[item.path] = item.component;
    });
  }
  
  //创建'router-link'和'router-view'组件
  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: '#' + this.to
          }
        }, [this.$slots.default])
      }
    });
    
    let _this = this;
    Vue.component('router-view', {
      render(h) {
        return h(_this.routerMap[_this.data.current])
      }
    });
  }

  initEvents() {
    //监听路由地址的变化
    window.addEventListener('hashchange', () => {
      this.data.current= window.location.hash.substr(1) ||'/';
    })
    //页面首次加载时，修改路径
    window.addEventListener('load', () => {
      if(window.location.href.indexOf('#') === -1) window.location.href += '#/';
    })
  }
}